import { netConfig } from '@/api/net.config'

// 基础类型定义（根据后端返回约定调整）
type HttpMethod = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
export interface ApiResponse<T = any> { code: number; data: T; msg?: string;[k: string]: any }
export interface RequestConfig {
  url: string
  method?: HttpMethod | Lowercase<HttpMethod>
  data?: any
  params?: any
  headers?: Record<string, string>
  silentError?: boolean
}

let tokenLose: boolean = true

// 由于 net.config 是 JS 文件，这里做最小类型约束
const NET = netConfig as unknown as { baseURL: string; contentType: string; requestTimeout: number }
const { baseURL, contentType, requestTimeout } = NET

// 基于 uni.request 的请求封装
export function request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
  return new Promise<ApiResponse<T>>((resolve, reject) => {
    // 获取token
    const token = uni.getStorageSync('token') as string | undefined
    // const token = TOKEN


    // 设置请求头
    const headers: Record<string, string> = {
      'Content-Type': contentType,
      ...(config.headers || {})
    };

    if (token) headers['Authorization'] = 'Bearer ' + token

    // 是否静默处理错误（不显示toast）
    const silentError = !!config.silentError

    // 构建完整URL
    const url = config.url.startsWith('http') ? config.url : baseURL + config.url
    const method = ((config.method || 'GET') + '').toUpperCase() as HttpMethod

    console.log('🌐 请求详情:', {
      method: config.method?.toUpperCase(),
      url: url,
      data: config.data || config.params,
      headers: headers
    });

    // 发送请求
    uni.request({
      url,
      method,
      data: config.data ?? config.params,
      header: headers,
      timeout: requestTimeout,
      success: (response: UniApp.RequestSuccessCallbackResult) => {
        console.log('🌐 响应详情:', {
          url: url,
          status: response.statusCode,
          data: response.data
        });

        const res = response.data as ApiResponse<T>

        // 请求成功处理
        if (res.code === 200) {
          resolve(res)
          return;
        }

        // 请求出错处理
        if (res.code === 405) {
          // token过期或无权限
          if (tokenLose) {
            tokenLose = false;
            uni.showModal({
              title: "提示",
              content: '登陆已过期，请重新登录！',
              cancelText: "取消",
              confirmText: '确定',
              confirmColor: 'red',
              success: (res) => {
                if (res.confirm) {
                  // 清除token并跳转到登录页
                  uni.removeStorageSync('token');
                  uni.removeStorageSync('user');
                  uni.reLaunch({
                    url: '/pages/login/login'
                  });
                }
              },
              complete: (res) => {
                tokenLose = true;
              }
            });
          }
          reject(res)
          return;
        }
        // 其他错误
        if (res.msg && !silentError) {
          uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000,
            mask: true // 添加遮罩层，提高层级
          });
        }
        reject(res)
      },
      fail: (error: UniApp.GeneralCallbackResult & { errMsg?: string }) => {
        console.error('❌ 请求失败:', error);

        // 网络错误提示
        let errorMessage = '网络请求失败';
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请重试';
          } else if (error.errMsg.includes('fail')) {
            errorMessage = '网络连接失败';
          } else {
            errorMessage = error.errMsg;
          }
        }

        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000,
          mask: true // 添加遮罩层，提高层级
        });
        reject({
          ...error,
          message: errorMessage
        } as any);
      }
    });
  });
}


// 白名单路径列表
const whiteList = [
  '/pages/login/login',
  '/pages/assistant-role/index',
  '/pages/manager-role/index',
  '/pages/franchisee-role/index'
];

// 添加导航拦截器
uni.addInterceptor('navigateTo', {
  invoke(args) {
    const token = uni.getStorageSync('token');
    console.log('token:', whiteList.some(path => args.url.includes(path)));
    // 检查是否在白名单中
    if (!whiteList.some(path => args.url.includes(path)) && !token) {
      uni.showModal({
        title: "提示",
        content: '检测到您还没有登陆，将跳转到登录页面',
        cancelText: "取消",
        confirmText: '确定',
        confirmColor: 'red',
        success: (res) => {
          if (res.confirm) {
            // 清除token并跳转到登录页
            uni.removeStorageSync('token');
            uni.removeStorageSync('user');
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }
        },
        complete: (res) => {

        }
      });
      return false;
    }
    return args;
  }
});

export default request;
